package com.baor.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    // 设置值
    public void setValue(String key, Object obj) {
        this.redisTemplate.opsForValue().set(key, obj);
    }

    // 设置值并设置过期时间
    public void setValue(String key, Object obj, long time, TimeUnit unit) {
        this.redisTemplate.opsForValue().set(key, obj, time, unit);
    }

    // 判断是否存在key
    public boolean containsKey(String key) {
        boolean flag = this.redisTemplate.hasKey(key);
        return flag;
    }

    // 获取值
    public Object getValue(String key) {
        return this.redisTemplate.opsForValue().get(key);
    }

    // 删除key
    public void delKey(String key) {
        this.redisTemplate.delete(key);
    }

    // 更新key
    public void updateKey(String key, Object obj) {
        setValue(key, obj);
    }

    // 更新key并设置过期时间
    public void updateKey(String key, Object obj, long time, TimeUnit unit) {
        if (time > 0) {
            setValue(key, obj, time, unit);
        } else {
            setValue(key, obj);
        }
    }

    // 设置hash值
    public Object getHash(String key, String hashKey) {
        return this.redisTemplate.opsForHash().get(key, hashKey);
    }
}
